// @ts-nocheck
import {useRoute} from 'vue-router';
import { reactive, ref } from 'vue'
import _ from 'lodash';
import OpenSeadragon from 'openseadragon';
import {fabric} from 'fabric';
import {ElMessage} from "element-plus";
import { Message } from '@arco-design/web-vue';
import * as Store from '@/store';
import { dataInfo, FabricToolOptions } from "./useInitData";
import useUtils from "./useUtils";
import useContainerUtils from '@/views/filmRead/hooks/useUtils';
import {
  delLesionData,
  saveAnnoData,
  updateAnnoData,
  updateAnnoType
} from '@/api/readPathology/readPathology';
import type {IEvent, Object as FrabicObject} from 'fabric/fabric-impl';

const HooksData = reactive({
  rightMenuVisable: false,//右键菜单显示
  rightMenuPosition: '',//右键菜单位置
  popVisible: false,//删除弹框显示
  selectedType: 0,//右键选中病灶类型
  selectOption: [] as any,//右键病灶类型下拉列表
})

const useEvents = (LeftHooks: Left.LeftHooks, initData: Function) => {
  const UtilsHooks = useUtils(initData);
  const ContainerUtilHooks = useContainerUtils();
  const FilmRead = Store.useFilmRead();
  const route = useRoute();
  const {type} = route;
  // const FilmReadHeader = Store.useFilmReadHeader();
  // const FilmReadLeft = Store.useFilmReadLeft();
  // const FilmReadRight = Store.useFilmReadRight();
  // const ToolBar = Store.useToolBar();
  const PicStore = Store.usePicContent();
  //更新时的鼠标点位
  let downPoint = { x: 0, y: 0 };
  let upPoint = { x: 0, y: 0 };
  // 初始注册鼠标事件
  const frabicMouseEvent = () => {
    dataInfo.frabicCanvas.off('mouse:down')
    dataInfo.frabicCanvas.off('mouse:up')
    dataInfo.frabicCanvas.on('mouse:down', fabricMousedown)
    if (type && type === "query") {
      dataInfo.frabicCanvas.off('object:modified')
      dataInfo.frabicCanvas.off('object:moving')
    } else {
      dataInfo.frabicCanvas.on("object:modified", fabricObjectModified)
      dataInfo.frabicCanvas.on("object:moving", fabricObjectMoving)
    }
    dataInfo.frabicCanvas.on('mouse:up', fabricMouseup)
    dataInfo.frabicCanvas.on('mouse:move', fabricMousemove)
    dataInfo.frabicCanvas.on('path:created', fabricPathCreated)
    dataInfo.frabicCanvas.on('selection:created', fabricSelectionCreated)
  };
  const fabricMousedown = (options: IEvent<MouseEvent>) => {
    //重置
    downPoint = {x: 0, y: 0};
    upPoint = {x: 0, y: 0};
    const offset = dataInfo.frabicCanvas.calcOffset().viewportTransform || [];
    if (options.target /*&& !dataInfo.doDrawing*/) {
      // 记录目标对象存在情况下的当前鼠标坐标
      const offsetX = offset[4];
      // 记录画布鼠标按下时的y偏移量
      const offsetY = offset[5];
      // 根据x偏移量计算实际x坐标
      const x: number = options.e.offsetX - offsetX;
      // 根据y偏移量计算实际y坐标
      const y: number = options.e.offsetY - offsetY;
      downPoint.x = x;
      downPoint.y = y;

      if (options.target.type !== 'group') {
        // 标注画布鼠标按下，并且标注存在，并让标注聚焦病灶列表
        const currentItemMarkObj = FilmRead.dictionaryData.imageDataList && FilmRead.dictionaryData.imageDataList[options.target?.id];
        // 设置当前选择的id，将病灶列表聚焦到当前选择病灶
        currentItemMarkObj && ContainerUtilHooks.lesionEvent.lesionSetActive(options.target?.id.toString(), true);
        // 根据当前选择的病灶设置当前聚焦的小征象
        dataInfo.isSelectObj = options.target;
        dataInfo.frabicCanvas.setActiveObject(options.target)//.renderAll();
        //图中选中path
        // options.target.type === 'CLOSEDCURVE' && UtilsHooks.addPathControl(options.target.id)
        // UtilsHooks.updateAnnoData()//太卡
      }
      if (options.button === 3){//右键
        HooksData.rightMenuVisable = true
        const lesionObj = FilmRead.dictionaryData.lesionDataList[options.target?.id]
        HooksData.selectOption = FilmRead.dictionaryData.toolList[lesionObj.tool].map(item => {
          return { ...FilmRead.dictionaryData.lesionList[item.lesion] }
        });
        //右键选中病灶框的病灶类型
        HooksData.selectedType = HooksData.selectOption.find(item => item.value === lesionObj.code).value;
        //
        const pointX = options.pointer.x
        const pointY = options.pointer.y
        HooksData.rightMenuPosition = `left: ${pointX}px;top: ${pointY}px;`
        dataInfo.doDrawing = true//不让画布移动
      }
    }else{
      HooksData.rightMenuVisable = false
    }
    const activeObj = dataInfo.frabicCanvas.getActiveObjects();
    activeObj.length === 0 && dataInfo.currentToolItem.currentItem && [5, 10, 11].includes(dataInfo.currentToolItem.currentItem.id) && mouseDown(options);
    if (!options.target) {
      dataInfo.isSelectObj = (null as unknown) as fabric.Object;
    }
  }
  const fabricObjectModified = async (options: IEvent<MouseEvent>) => {
    const { target } = options
    const { type, _objects } = target
    //path的编辑不一样，每次新建
    if (type === 'CLOSEDCURVE') {
      await closedcurveModified(options)
    } else if (['rect', 'ellipse'].includes(type)) {
      await rectEllipseModified(options)
    } else if(type === 'path-control'){//path单点编辑
      await singlePathcontrolModified(options)
    } else if(Array.isArray(_objects) && _objects.every(o => o.type === 'path-control')){
      await multiPathcontrolModified(options)
    } else {
      //todo 其他overlay
    }
  }
  //闭合曲线平移
  const closedcurveModified = async (ev) => {
    const {action, by, e, target, transform} = ev
    const {id, stroke, strokeWidth, fill, acZoom} = target
    const matrix = target.calcTransformMatrix();
    const transformedPoints = target.path.map(function (p: any) {
      // fabric的
      if (p[3] && p[4]) {
        const point1 = fabric.util.transformPoint(
            new fabric.Point(p[1] - target.pathOffset.x, p[2] - target.pathOffset.y),
            matrix
        );
        const point2 = fabric.util.transformPoint(
            new fabric.Point(p[3] - target.pathOffset.x, p[4] - target.pathOffset.y),
            matrix
        );
        return [p[0], point1.x, point1.y, point2.x, point2.y];
      }
      if (p[1] && p[2]) {
        const point = fabric.util.transformPoint(
            new fabric.Point(p[1] - target.pathOffset.x, p[2] - target.pathOffset.y),
            matrix
        );
        return [p[0], point.x, point.y];
      }
      if (!p[1]) {
        return [p[0]]
      }
    });
    const newPath = new fabric.Path(transformedPoints.flat().join(" "), {
      ...FabricToolOptions,
      id,
      type: target.type,
      stroke,
      strokeWidth,
      fill,
      acZoom
    })
    dataInfo.frabicCanvas.remove(target).add(newPath)
    dataInfo.frabicCanvas.setActiveObject(newPath).renderAll();
    //保存
    const pathArr = UtilsHooks.pathPointConvert(newPath.path, UtilsHooks.fabricToImage)
    const currentCanvasObj = FilmRead.dictionaryData.imageDataList && FilmRead.dictionaryData.imageDataList[LeftHooks.leftHooksData.currentIndex];
    const currentLesionObj = FilmRead.dictionaryData.lesionDataList && FilmRead.dictionaryData.lesionDataList[LeftHooks.leftHooksData.currentIndex];
    if (currentCanvasObj && currentLesionObj) {
      const {id, result} = currentCanvasObj;
      const {color} = currentLesionObj;
      const {acZoom, version} = result;
      //处理精度，保留整数
      const path = pathArr.map(item => {
        return item.map(p => {
          if(typeof p === 'number'){
            return Math.round(p)
          }else{
            return p
          }
        })
      })
      const resultData = {
        path
      };
      const resultDataObj = {
        data: _.cloneDeep(resultData),
        acZoom,
        version,
      };
      const params = {
        alrId: id,
        result: JSON.stringify(_.cloneDeep(resultDataObj)),
        color: color,
      };
      const res = await updateAnnoData(params);
      ElMessage.success('修改成功！');
      currentCanvasObj.result = JSON.parse(params.result);
      UtilsHooks.updateAnnoData(e)
    }
  }
  //矩形or椭圆编辑
  const rectEllipseModified = async (ev) => {
    const {action, by, e, target, transform} = ev
    const {id, left, top, width, height, scaleX, scaleY, rx, ry} = target
    let pp1 = UtilsHooks.changePoint({x: left, y: top}, true)//实际大图值
    let pp2 = UtilsHooks.changePoint({x: left + width * scaleX, y: top + height * scaleY}, true)//实际大图值
    //恢复对象拉伸，直接=赋值会抖
    target.set('width', width * scaleX)
    target.set('height', height * scaleY)
    target.set('rx', rx * scaleX)
    target.set('ry', ry * scaleY)
    target.set('scaleX', 1)
    target.set('scaleY', 1)
    const currentCanvasObj = FilmRead.dictionaryData.imageDataList && FilmRead.dictionaryData.imageDataList[LeftHooks.leftHooksData.currentIndex];
    const currentLesionObj = FilmRead.dictionaryData.lesionDataList && FilmRead.dictionaryData.lesionDataList[LeftHooks.leftHooksData.currentIndex];
    if (currentCanvasObj && currentLesionObj) {
      // 通过得到的当前数据对象解构出相应宽度，高度，left值，top值做后续处理
      const {id, result, ...otherCanvas} = currentCanvasObj;
      const {color, ...otherLesion} = currentLesionObj;
      const {data, acZoom, version} = result;
      //控制精度，取整
      pp1.x = Math.round(pp1.x)
      pp1.y = Math.round(pp1.y)
      pp2.x = Math.round(pp2.x)
      pp2.y = Math.round(pp2.y)
      const resultData2 = {
        point1: {...pp1},
        point2: {...pp2},
      };
      const resultDataObj2 = {
        data: _.cloneDeep(resultData2),
        acZoom,
        version,
      };
      const params2 = {
        alrId: id,
        result: JSON.stringify(_.cloneDeep(resultDataObj2)),
        color: color,
      };
      const res = await updateAnnoData(params2);
      ElMessage.success('修改成功！');
      currentCanvasObj.result = JSON.parse(params2.result);
      // UtilsHooks.updateAnnoData()
    }
  }
  //path单个控制点编辑
  const singlePathcontrolModified = async (ev) => {
    const {action, by, e, target, transform} = ev
    const {id, left, top, width, height} = target
    //修改path的点时去更新path
    const currPathArr = UtilsHooks.getOverlaysByIdAndType(id, 'CLOSEDCURVE')
    //替换坐标
    // console.log('前',currPathArr[0].path)
    if(currPathArr.length > 0 && currPathArr[0].path){
      const x = left + target.radius
      const y = top + target.radius
      const p = currPathArr[0].path[target.idx]
      if(p[0] === 'M' || p[0] === 'L'){
        p.splice(1,2,x,y)
      }else if(p[0] === 'Q'){
        const moveX = x - p[3]
        const moveY = y - p[4]
        p.splice(1,4,p[1] + moveX, p[2] + moveY,x,y)
        // p.splice(3,2,x,y)
      }
      currPathArr[0].set('dirty', true)
    }
    // console.log('后',currPathArr[0].path)
    //保存
    const pathArr = UtilsHooks.pathPointConvert(currPathArr[0].path, UtilsHooks.fabricToImage)
    const currentCanvasObj = FilmRead.dictionaryData.imageDataList && FilmRead.dictionaryData.imageDataList[LeftHooks.leftHooksData.currentIndex];
    const currentLesionObj = FilmRead.dictionaryData.lesionDataList && FilmRead.dictionaryData.lesionDataList[LeftHooks.leftHooksData.currentIndex];
    if (currentCanvasObj && currentLesionObj) {
      const {id, result} = currentCanvasObj;
      const {color} = currentLesionObj;
      const {acZoom, version} = result;
      const resultData = {
        path: pathArr
      };
      const resultDataObj = {
        data: _.cloneDeep(resultData),
        acZoom,
        version,
      };
      const params = {
        alrId: id,
        result: JSON.stringify(_.cloneDeep(resultDataObj)),
        color: color,
      };
      const res = await updateAnnoData(params);
      ElMessage.success('修改成功！');
      currentCanvasObj.result = JSON.parse(params.result);
      // dataInfo.frabicCanvas.renderAll()
      UtilsHooks.updateAnnoData(e)
    }
  }
  //path多个控制点编辑
  const multiPathcontrolModified = async (ev) => {
    const {action, by, e, target, transform} = ev
    const {id, left, top, width, height} = target
    //path 多点编辑
    const { id: pathId} = target._objects[0]
    const currPathArr = UtilsHooks.getOverlaysByIdAndType(pathId, 'CLOSEDCURVE')
    //替换坐标
    target._objects.map((it) => {
      const matrix = it.calcTransformMatrix();
      /*const point1 = fabric.util.transformPoint(
          new fabric.Point(it.left + it.radius, it.top + it.radius),
          matrix
      );*/
      const x = matrix[4]//point1.x//left - it.left - it.radius//
      const y = matrix[5]//point1.y//top - it.top - it.radius//
      const p = currPathArr[0].path[it.idx]
      if(p[0] === 'M' || p[0] === 'L'){
        p.splice(1,2,x,y)
      }else if(p[0] === 'Q'){
        const moveX = x - p[3]
        const moveY = y - p[4]
        p.splice(1,4,p[1] + moveX, p[2] + moveY,x,y)
      }
    })
    // currPathArr[0].set('dirty', true)
    //保存
    const pathArr = UtilsHooks.pathPointConvert(currPathArr[0].path, UtilsHooks.fabricToImage)
    const currentCanvasObj = FilmRead.dictionaryData.imageDataList && FilmRead.dictionaryData.imageDataList[LeftHooks.leftHooksData.currentIndex];
    const currentLesionObj = FilmRead.dictionaryData.lesionDataList && FilmRead.dictionaryData.lesionDataList[LeftHooks.leftHooksData.currentIndex];
    if (currentCanvasObj && currentLesionObj) {
      const {id, result} = currentCanvasObj;
      const {color} = currentLesionObj;
      const {acZoom, version} = result;
      const resultData = {
        path: pathArr
      };
      const resultDataObj = {
        data: _.cloneDeep(resultData),
        acZoom,
        version,
      };
      const params = {
        alrId: id,
        result: JSON.stringify(_.cloneDeep(resultDataObj)),
        color: color,
      };
      const res = await updateAnnoData(params);
      ElMessage.success('修改成功！');
      currentCanvasObj.result = JSON.parse(params.result);
      dataInfo.frabicCanvas.renderAll()
      // UtilsHooks.updateAnnoData(e)
    }
  }
  const fabricObjectMoving = async (options: IEvent<MouseEvent>) => {
    const {action, by, e, target, transform} = options
    const {id, idx,left, top, width, height, scaleX, scaleY, rx, ry, stroke, strokeWidth, radius, acZoom} = target
  }
  const fabricMouseup = async (options: IEvent<MouseEvent>) => {
    const { target } = options
    if (dataInfo.currentToolItem.currentItem) {
      [5, 10, 11].includes(dataInfo.currentToolItem.currentItem.id) && mouseUp(options);
    }
    //选中path
    if(target && target.type === 'CLOSEDCURVE' && route.query.type !== 'query'){
      // UtilsHooks.updateAnnoData()
      UtilsHooks.removePathControl(target.id)
      UtilsHooks.addPathControl(target.id)
    }
  }
  const fabricMousemove = (options: IEvent<MouseEvent>) => {
    if (options.target || dataInfo.doDrawing) {
      dataInfo.viewer.setMouseNavEnabled(false);
    } else {
      dataInfo.viewer.setMouseNavEnabled(true);
    }
  }
  const fabricPathCreated = (options: IEvent<MouseEvent>) => {
    // console.log('path.created', options)
    const {id} = dataInfo.currentToolItem.currentItem
    if (id === 12) {//闭合曲线
      options.path.type = dataInfo.currentToolItem.currentItem.code
      FabricToolOptions.type = dataInfo.currentToolItem.currentItem.code
      FabricToolOptions.acZoom = dataInfo.viewer.viewport.getZoom() / UtilsHooks.getActualNum();
      const {path: pathPointArr} = options.path
      pathPointArr.push(['Z'])//闭合
      //覆盖默认样式
      options.path.setOptions({...FabricToolOptions, stroke: dataInfo.currentToolItem.lesion.color})
      dataInfo.canvasObject = options.path
      const pathArr = UtilsHooks.pathPointConvert(pathPointArr, UtilsHooks.fabricToImage)
      //保存、设置id
      savePathMark(pathArr)
    }
  }
  const fabricSelectionCreated = (options: IEvent<MouseEvent>) => {
    const { target } = options
    if(target.type === 'activeSelection'){
      // target.set('_controlsVisibility', { mtr: false,bl: false,br: false,mb: false,ml: false,mr: false,mt: false,tl: false,tr: false })
      target.set('hasControls', false)
      target.set('borderColor', "grey")
      target.set('borderDashArray', [3,1])
      // target.set('fill', "#018")
      // target.set('selectionBackgroundColor', "#f11000")
      // target.set('stroke', "#ccc")
    }
  }
  // 鼠标按下
  const mouseDown = (options: IEvent<MouseEvent>) => {
    const offset = dataInfo.frabicCanvas.calcOffset().viewportTransform || [];
    // 记录画布鼠标按下时的x偏移量
    const offsetX = offset[4];
    // 记录画布鼠标按下时的y偏移量
    const offsetY = offset[5];
    // 根据x偏移量计算实际x坐标
    const x = options.e.offsetX - offsetX;
    // 根据y偏移量计算实际y坐标 
    const y = options.e.offsetY - offsetY;
    // 存储x坐标
    dataInfo.mouseFrom.x = x;
    // 存储y坐标
    dataInfo.mouseFrom.y = y;
    // 当前点击的坐标并创建成openseadragon的点位
    const pos = new OpenSeadragon.Point(options.e.x, options.e.y);
    // 根据当前openseadragon的点位将window的点位转换成图片上的点位
    const imagePos = dataInfo.viewer.viewport.windowToImageCoordinates(pos);
    // 根据window所在图片上的点位查看当前点位是否超过图像区域，否则禁止绘制
    /*if (
      imagePos.x < 0 ||
      imagePos.x > Number(dataInfo.slideInfo.Width) ||
      imagePos.y < 0 ||
      imagePos.y > Number(dataInfo.slideInfo.Height)
    ) {
      dataInfo.doDrawing = false;
      dataInfo.frabicCanvas.skipTargetFind = false;
      dataInfo.frabicCanvas.selectionColor = 'transparent';
      dataInfo.frabicCanvas.selectionBorderColor = '#1FFF79';
    } else {
      dataInfo.doDrawing = true;
      // dataInfo.frabicCanvas.skipTargetFind = true;
      dataInfo.frabicCanvas.selectionColor = 'transparent';
      dataInfo.frabicCanvas.selectionBorderColor = dataInfo.pencilColor;
    }*/
  };
  // 鼠标抬起
  const mouseUp = (options: IEvent<MouseEvent>) => {
    const offset = dataInfo.frabicCanvas.calcOffset().viewportTransform || [];
    const offsetX = offset[4];
    const offsetY = offset[5];
    dataInfo.mouseTo.x = options.e.offsetX - offsetX;
    dataInfo.mouseTo.y = options.e.offsetY - offsetY;
    // 过滤掉鼠标之间按下抬起没画任何图形
    if (
        (dataInfo.mouseFrom.x === dataInfo.mouseTo.x &&
            dataInfo.mouseFrom.y === dataInfo.mouseTo.y) ||
        options.target
    ) {
      // 最后绘制的标注存在并重置属性，以免出现绘制不上去问题
      resetCanvasOption();
      return;
    }
    // 画图像
    drawMark();
  };
  // 重置画布
  const resetCanvasOption = () => {
    // dataInfo.doDrawing = false;
    dataInfo.canvasObject = (null as unknown) as fabric.Object;
    dataInfo.groupObject = (null as unknown) as fabric.Group;
    dataInfo.textObject = (null as unknown) as fabric.Text;
    // dataInfo.isSelectObj = (null as unknown) as fabric.Object;
    dataInfo.mouseFrom = {
      x: 0,
      y: 0,
    };
    dataInfo.mouseTo = {
      x: 0,
      y: 0,
    };
    // dataInfo.frabicCanvas.off('mouse:down');
    // dataInfo.frabicCanvas.off('mouse:up');
  };
  // 新建标注图形
  const drawMark = () => {
    // 判断当前绘制锁状态 为true允许绘制
    if (dataInfo.doDrawing && dataInfo.viewer) {
      // 减少绘制频率
      if (!dataInfo.doDrawing) return;
      FabricToolOptions.acZoom = dataInfo.viewer.viewport.getZoom() / UtilsHooks.getActualNum();
      // 通过当前病灶变更初始笔刷颜色
      if ([10, 11].includes(dataInfo.currentToolItem.currentItem.id)) {
        dataInfo.currentToolItem.lesion && (FabricToolOptions.stroke = dataInfo.currentToolItem.lesion.color);
      } else {
        FabricToolOptions.stroke = dataInfo.pencilColor;
      }
      // 尺子长度
      // 长度
      const LWindth = Math.abs(dataInfo.mouseTo.x - dataInfo.mouseFrom.x);
      const LHeight = Math.abs(dataInfo.mouseTo.y - dataInfo.mouseFrom.y);
      const lineLength = Math.round(Math.sqrt(LWindth * LWindth + LHeight * LHeight) * 100) / 100;
      // 椭圆相关值
      const rx = Math.abs(dataInfo.mouseFrom.x - dataInfo.mouseTo.x) / 2;
      const ry = Math.abs(dataInfo.mouseFrom.y - dataInfo.mouseTo.y) / 2;
      const top =
          dataInfo.mouseTo.y > dataInfo.mouseFrom.y
              ? dataInfo.mouseFrom.y
              : dataInfo.mouseFrom.y - ry * 2;
      const left =
          dataInfo.mouseTo.x > dataInfo.mouseFrom.x
              ? dataInfo.mouseFrom.x
              : dataInfo.mouseFrom.x - rx * 2;
      if (dataInfo.currentToolItem.currentItem.id === 5) {
        // 尺子
        FabricToolOptions.type = 'line';
        dataInfo.canvasObject = new fabric.Line(
            [
              dataInfo.mouseFrom.x,
              dataInfo.mouseFrom.y,
              dataInfo.mouseTo.x,
              dataInfo.mouseTo.y,
            ],
            {
              ...FabricToolOptions,
              transparentCorners: false,
              hasControls: false,
              lockScalingX: true,
              lockScalingY: true,
              lockRotation: true,
              lockMovementX: true,
              lockMovementY: true,
              perPixelTargetFind: true,
              stroke: dataInfo.ruleInfo.color
            }
        );
        dataInfo.textObject = new fabric.Text(`${lineLength}mm`, {
          top: dataInfo.mouseTo.y,
          left: dataInfo.mouseTo.x,
          fontSize: 16,
          transparentCorners: false,
          hasControls: false,
          lockScalingX: true,
          lockScalingY: true,
          lockRotation: true,
          lockMovementX: true,
          lockMovementY: true,
          perPixelTargetFind: true,
          stroke: dataInfo.ruleInfo.color
          // originX: 'center',
          // originY: 'center',
        });
        /*dataInfo.groupObject = new fabric.Group(
          [dataInfo.canvasObject, textObject],
          {
            type: 'group',
            // borderColor: 'transparent', // 边框颜色
            // cornerColor: 'transparent', // 控制角颜色
            // cornerSize: 10, // 控制角大小
            // 控制器是否为填充 true为透明 false为填充
            transparentCorners: false,
            hasControls: false,
            lockScalingX: true,
            lockScalingY: true,
            lockRotation: true,
            lockMovementX: true,
            lockMovementY: true,
            perPixelTargetFind: true,
          }
        );
        dataInfo.frabicCanvas.add(dataInfo.groupObject);*/
        const uuid = new Date().valueOf()
        dataInfo.canvasObject.set('id', uuid)
        dataInfo.canvasObject.set('acZoom', FabricToolOptions.acZoom)
        dataInfo.textObject.set('id', uuid)
        dataInfo.textObject.set('acZoom', FabricToolOptions.acZoom)
        dataInfo.textObject.set('lineLength', lineLength)
        dataInfo.textObject.lineLength = lineLength
        dataInfo.frabicCanvas.add(dataInfo.canvasObject, dataInfo.textObject).renderAll()
        // 保存
        saveMark();
      }
      if (dataInfo.currentToolItem.currentItem.id === 10) {
        // 矩形
        FabricToolOptions.type = 'rect';
        FabricToolOptions.borderColor = '#1FFF79';
        FabricToolOptions.cornerColor = '#1FFF79';
        FabricToolOptions.cornerSize = 5;
        dataInfo.canvasObject = new fabric.Rect({
          top: Math.min(dataInfo.mouseFrom.y, dataInfo.mouseTo.y),
          left: Math.min(dataInfo.mouseFrom.x, dataInfo.mouseTo.x),
          width: Math.abs(dataInfo.mouseFrom.x - dataInfo.mouseTo.x),
          height: Math.abs(dataInfo.mouseFrom.y - dataInfo.mouseTo.y),
          ...FabricToolOptions,
        });
        dataInfo.frabicCanvas.add(dataInfo.canvasObject);
        // 保存
        saveMark();
      }
      if (dataInfo.currentToolItem.currentItem.id === 11) {
        // 椭圆
        FabricToolOptions.type = 'ellipse';
        FabricToolOptions.borderColor = '#1FFF79';
        FabricToolOptions.cornerColor = '#1FFF79';
        FabricToolOptions.cornerSize = 5;
        dataInfo.canvasObject = new fabric.Ellipse({
          top,
          left,
          rx,
          ry,
          ...FabricToolOptions,
        });
        dataInfo.frabicCanvas.add(dataInfo.canvasObject);
        // 保存
        saveMark();
      }
    }
  };
  // 调用接口保存
  const saveMark = async () => {
    if (dataInfo.currentToolItem.currentItem.id === 5 && dataInfo.viewer) {
      const markObjItem = _.cloneDeep({
        id: dataInfo.canvasObject.id,
        data: {
          point1: {...UtilsHooks.changePoint(dataInfo.mouseFrom, true)},
          point2: {...UtilsHooks.changePoint(dataInfo.mouseTo, true)},
        },
        acZoom: FabricToolOptions.acZoom,
        lineLength: dataInfo.textObject.lineLength
      });
      PicStore.setArr(markObjItem);
      resetCanvasOption();
    }
    if (dataInfo.currentToolItem.currentItem.id === 10 || dataInfo.currentToolItem.currentItem.id === 11) {
      // 处理数据保存为左侧病灶列表
      let point1 = {...UtilsHooks.changePoint(dataInfo.mouseFrom, true)}
      let point2 = {...UtilsHooks.changePoint(dataInfo.mouseTo, true)}
      //保留整数
      point1.x = Math.round(point1.x)
      point1.y = Math.round(point1.y)
      point2.x = Math.round(point2.x)
      point2.y = Math.round(point2.y)
      const tempObj = {
        data: {
          point1,
          point2,
        },
        acZoom: FabricToolOptions.acZoom,
        version: '4.6.0',
      };
      // let newType = '';
      // if (dataInfo.currentToolItem.toolType === 'rect') newType = 'RECTANGLE';
      // if (dataInfo.currentToolItem.toolType === 'ellipse') newType = 'ELLIPSE';
      const markResultObj = {
        lesion: dataInfo.currentToolItem.lesion!.lesion,
        color: dataInfo.currentToolItem.lesion!.color,
        tool: dataInfo.currentToolItem.currentItem.toolType,
        result: JSON.stringify(tempObj),
      };
      // 保存数据
      const params = {
        arId: FilmRead.interfaceData.seriesList[FilmRead.currentThumbnailIndex].id,
        ...markResultObj,
      };
      const res = await saveAnnoData(params);
      ElMessage.success('新增标注成功！');
      // 追加数据
      markResultObj.result = tempObj
      ContainerUtilHooks.lesionEvent.lesionAdd({...markResultObj, id: res.data.alrId ?? res.alrId});
      // 对图形追加id否则影响后续变更逻辑
      if (dataInfo.canvasObject) {
        dataInfo.canvasObject.set("id", res.data.alrId ?? res.alrId);
      } else {
        console.log('id设置失败', res.data.alrId ?? res.alrId)
      }
      resetCanvasOption();
      // refreshCanvas();
      dataInfo.viewer.setMouseNavEnabled(false);
      const canvasObjs = dataInfo.frabicCanvas.getObjects();
      const addCanvasObj = canvasObjs.find(item => item.id === res.data.alrId ?? res.alrId);
      if (addCanvasObj) {
        dataInfo.frabicCanvas.setActiveObject(addCanvasObj).renderAll();
      } else {
        console.log('聚焦失败', res.data.alrId ?? res.alrId)
      }
    }
  };
  // path接口保存
  const savePathMark = async (pathArr: []) => {
    if (dataInfo.currentToolItem.currentItem.id === 12) {
      //处理精度，保留整数
      const path = pathArr.map(item => {
        return item.map(p => {
          if(typeof p === 'number'){
            return Math.round(p)
          }else{
            return p
          }
        })
      })
      // 处理数据保存为左侧病灶列表
      const tempObj = {
        data: {
          path
        },
        acZoom: FabricToolOptions.acZoom,
        version: '4.6.0',
      };
      const markResultObj = {
        lesion: dataInfo.currentToolItem.lesion!.lesion,
        color: dataInfo.currentToolItem.lesion!.color,
        tool: FabricToolOptions.type,
        result: JSON.stringify(tempObj),
      };
      // 保存数据
      const params = {
        arId: FilmRead.interfaceData.seriesList[FilmRead.currentThumbnailIndex].id,
        ...markResultObj,
      };
      const res = await saveAnnoData(params);
      ElMessage.success('新增标注成功！');
      // 追加数据
      const id = res.data.alrId ?? res.alrId
      markResultObj.result = tempObj
      ContainerUtilHooks.lesionEvent.lesionAdd({...markResultObj, id});
      // 对图形追加id否则影响后续变更逻辑
      if (dataInfo.canvasObject) {
        dataInfo.canvasObject.set("id", id);
      } else {
        console.log('id设置失败', id)
      }
      resetCanvasOption();
      dataInfo.viewer.setMouseNavEnabled(false);
      const canvasObjs = dataInfo.frabicCanvas.getObjects();
      const addCanvasObj = canvasObjs.find(item => item.id === id);
      if (addCanvasObj) {
        dataInfo.frabicCanvas.setActiveObject(addCanvasObj).renderAll();
      } else {
        console.log('聚焦失败', id)
      }
    }
  };
  // 重置画布
  const refreshCanvas = () => {
    dataInfo.frabicCanvas.clear();
  }
  //右键病灶类型变更
  const handleChange = async (val) => {
    //调用接口
    const currentObj = dataInfo.frabicCanvas.getActiveObject()
    const params = {'alrId': currentObj.id, 'lesion': val}
    const { code, msg } = await updateAnnoType(params);
    if(code === 200){
      //更新缓存数据
      const tempObj = HooksData.selectOption.find(item => item.value === val);
      FilmRead.dictionaryData.lesionDataList[currentObj.id].lesion = tempObj.name;
      ElMessage.success('修改成功');
    }else {
      ElMessage.success(msg);
    }
  }
  //显示右键删除确认框
  const showDelConfirm = (flag: boolean) => {
    HooksData.popVisible = ((flag !==undefined)? flag : !HooksData.popVisible)
  }
  //右键删除api
  const rightDelClick = async () => {
    const currentObj = dataInfo.frabicCanvas.getActiveObject();
    const { code } = await delLesionData(String(currentObj.id));
    if(code === 200){
      Message.success('删除成功');
      currentObj && dataInfo.frabicCanvas.remove(currentObj).renderAll()
      ContainerUtilHooks.lesionEvent.lesionDel(currentObj.id);
    }else{
      Message.success('删除失败,请刷新数据！');
    }
    showDelConfirm(false)
    HooksData.rightMenuVisable = false
  }

  let currentType = false;
  let primaryDown = false;
  let nonPrimaryDown = false;
  let dragPosition = {
    x: 0,
    y: 0,
  };
  let zoomPositon = {
    x: 0,
    y: 0,
  };
  // 大图事件
  const pictureEvent = () => {
    dataInfo.mouseTracker?.setTracking(true);
    const moveHandler = (event: any) => {
      // 1是左键 0是移动 2是右键
      // if (event.buttons === 0 || event.buttons === 1) {
      //     if ([4, 6, 7].includes(currentItem.value)) {
      //         viewer.value.setMouseNavEnabled(false);
      //     }
      // }
      if (event.buttons === 2) {
        if (nonPrimaryDown) {
          const delta = event.position.minus(dragPosition);
          dataInfo.viewer?.viewport.panBy(
              dataInfo.viewer?.viewport.deltaPointsFromPixels(delta.negate())
          );
          dragPosition = event.position.clone();
        }
      }
    };
    let canvasDownPoint = {
      x: 0,
      y: 0,
    };
    // 鼠标移动
    dataInfo.mouseTracker && (dataInfo.mouseTracker.moveHandler = moveHandler);
    dataInfo.viewer?.addHandler('canvas-press', (event: any) => {
      canvasDownPoint = event.position.clone();
      if ((dataInfo.currentToolItem.currentItem && [2, 3].includes(dataInfo.currentToolItem.currentItem.id)) || currentType || dataInfo.isDefault) {
        // [2, 3].includes(ToolBar.currentItem)为查看工具类
        // currentType为空格按键时
        // 初始时isDefault.value以及点击重置
        primaryDown = true;
        zoomPositon = event.position.clone();
      }
    });
    dataInfo.viewer?.addHandler('canvas-release', (event: any) => {
      primaryDown = false;
    });
    //鼠标平移缩放
    dataInfo.viewer?.addHandler('canvas-drag', (event: any) => {
      const {delta: {y: up}, position: {x, y}} = event
      if (_.isEmpty(dataInfo.currentToolItem) || (dataInfo.currentToolItem.currentItem && dataInfo.currentToolItem.currentItem.id === 2)) {
        let ratio = 1.01
        dataInfo.viewer?.viewport.zoomBy(
            Math.pow(ratio, up),
            dataInfo.viewer?.viewport.pointFromPixel(new OpenSeadragon.Point(x, y), false)
        );
      }
      // UtilsHooks.updateAnnoData()
    });
    dataInfo.viewer?.addHandler('canvas-nonprimary-press', (event: any) => {
      if (event.button === 2) {
        nonPrimaryDown = true;
        dragPosition = event.position.clone();
      }
    });
    dataInfo.viewer?.addHandler('canvas-nonprimary-release', (event: any) => {
      if (event.button === 2) {
        nonPrimaryDown = false;
        dataInfo.viewer?.viewport.applyConstraints();
      }
    });
    // 鼠标滚动计算标注
    /*dataInfo.viewer?.addHandler('canvas-scroll', _.throttle(scrollData, 0, { 'leading': false }));*/
    // viewport change callback
    //防抖?throttle 100,{ leading: false, trailing: true })
    dataInfo.viewer?.addHandler('viewport-change',(e) => {
      UtilsHooks.updateAnnoData(e)
    });
  };

  // 键盘事件
  const keyDownEvent = () => {
    const listenerDom = document.getElementById('content-viewer-container')!;
    listenerDom.addEventListener('keydown', (event: any) => {
      const currentLesionObj = FilmRead.dictionaryData.lesionDataList && FilmRead.dictionaryData.lesionDataList[LeftHooks.leftHooksData.currentIndex];
      const keyNum = window.event ? event.keyCode : event.which;
      if (keyNum === 32) {//空格
        currentType = !currentType;
      }else if(keyNum === 17){//ctrl
        if(currentLesionObj && currentLesionObj.tool === 'CLOSEDCURVE'){//闭合曲线
          dataInfo.doDrawing = true;
        }
      }
      //todo 上下左右快捷键
      /*else if([37,38,39,40].includes(keyNum)){//left|up|right|down arrow
        if(currentLesionObj && currentLesionObj.tool === 'CLOSEDCURVE'){//闭合曲线
          const activeObject = dataInfo.frabicCanvas.getActiveObject()
          if(!activeObject || activeObject.type !== 'activeSelection') return
          const moveStep = 2;
          (keyNum === 37) && activeObject.set({'left': activeObject.left - moveStep});
          (keyNum === 38) && activeObject.set({'top': activeObject.top - moveStep});
          (keyNum === 39) && activeObject.set({'left': activeObject.left + moveStep});
          (keyNum === 40) && activeObject.set({'top': activeObject.top + moveStep});
          multiPathcontrolModified({e: event, target: activeObject})
        }
      }*/
    });
    listenerDom.addEventListener('keyup', (event: any) => {
      const keyNum = window.event ? event.keyCode : event.which;
      if (keyNum === 32) {//空格
        /*const enabled = dataInfo.viewer.isMouseNavEnabled();
        if (!currentType) {
          dataInfo.viewer.setMouseNavEnabled(false);
          frabicMouseEvent();
          ElMessage.info('已切换为绘制模式！');
          // debounce(Message.info('已切换为绘制模式！'), 500)
        } else {
          dataInfo.viewer?.setMouseNavEnabled(true);
          ElMessage.info('已切换为查看模式！');
          dataInfo.viewer && (dataInfo.viewer.zoomPerScroll = 1.1);
          dataInfo.viewer && (dataInfo.viewer.panHorizontal = true);
          dataInfo.viewer && (dataInfo.viewer.panVertical = true);
          pictureEvent();
        };*/
      }else if(keyNum === 17){//ctrl
        const currentLesionObj = FilmRead.dictionaryData.lesionDataList && FilmRead.dictionaryData.lesionDataList[LeftHooks.leftHooksData.currentIndex];
        if(currentLesionObj && currentLesionObj.tool === 'CLOSEDCURVE'){//闭合曲线
          dataInfo.doDrawing = false;
        }
      }
    });
  };

  return {
    HooksData,
    frabicMouseEvent,
    pictureEvent,
    keyDownEvent,
    showDelConfirm,
    rightDelClick,
    handleChange
  };
};

export default useEvents;
